package com.pn.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.pn.constant.AuthServerConstant;
import com.pn.entity.SysLoginUser;
import com.pn.mapper.SysLoginUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
public class LoginUserDetailsService implements UserDetailsService {

    //注入SysLoginUserMapper
    @Autowired
    private SysLoginUserMapper userMapper;

    //从数据库查询用户信息及用户的权限信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //获取请求头loginType的值
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String loginType = request.getHeader(AuthServerConstant.LOGIN_TYPE);

        if(StringUtils.hasText(loginType)){
            switch(loginType){
                //后台系统用户登录
                case AuthServerConstant.SYS_USER:
                    //根据用户名查询用户 --- select * from sys_user where username = ? and status = 1
                    SysLoginUser loginUser = userMapper.selectOne(
                            new LambdaQueryWrapper<SysLoginUser>()
                                    .eq(SysLoginUser::getUsername, username)
                                    .eq(SysLoginUser::getStatus, 1)
                    );
                    if(loginUser!=null){
                        //根据用户id查询用户权限
                        List<String> allAuthorities = userMapper.findAuthoritiesById(loginUser.getUserId());
                        if(!CollectionUtils.isEmpty(allAuthorities)){
                            loginUser.setAllAuthorities(allAuthorities);
                        }
                    }
                    return loginUser;

                //前台系统用户登录
                case AuthServerConstant.USER:
                    /*
                      前台系统用户的认证方式：
                     */
            }
        }

        return null;
    }
}
